//
//  ZGLiveView.swift
//  ZhangGuang
//
//  Created by 叁拾叁 on 2020/7/20.
//  Copyright © 2020 叁拾叁. All rights reserved.
//
/*
import UIKit
import EZOpenSDKFramework
import TZImagePickerController
import Toast
import SnapKit
import SwiftWeb

class ZGLiveView: UIView, EZPlayerDelegate, TZImagePickerControllerDelegate, ZGAudioRecorderProtocol {
    
    weak var liveProtocol: ZGLiveProtocol!
    weak var currentVC: HSWebViewController!
    var recoder: ZGAudioRecorder = ZGAudioRecorder()
    var maxCnt: NSInteger = 2 //失败重新加载最大次数
    var picParams = Dictionary<String, Any>()
    var PTZParams = Dictionary<String, Any>()
    var accessTokenParams = Dictionary<String, Any>()
    var blanner: UIView?
    var player: EZPlayer?//视频播放
    var talkPlayer: EZPlayer?//视频对讲
    var commandType: EZPTZCommand = .up
    var cameraNo: NSInteger = 0
    var deviceSerial = ""
    var canTakePhoto: Bool!
    var middleView: ZGLiveMiddleView? = {
        let v = ZGLiveMiddleView()
        
        return v
    }()
    var topView: ZGLiveTopView? = {
        let v = ZGLiveTopView()
        v.backgroundColor = UIColor(white: 0, alpha: 0.5)
        return v
    }()
    var bottomView: ZGLiveBottomView? = {
        let v = ZGLiveBottomView()
        v.backgroundColor = UIColor(white: 0, alpha: 0.5)
        return v
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        blanner = UIView(frame: self.frame)
        blanner!.backgroundColor = UIColor.black
        blanner!.isHidden = true
        recoder.delegate = self
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    func setRotatDirection(_ index: Int, _ length: Double) {
        
        // 操作命令：0-上，1-下，2-左，3-右，4-左上，5-左下，6-右上，7-右下，8-放大，9-缩小，10-近焦距，11-远焦距
        switch index {
        case 0:
            print("向上滑动");
            self.PTZParams["direction"] = 0
        case 1:
            print("向下滑动");
            self.PTZParams["direction"] = 1
        case 2:
            print("向左滑动");
            self.PTZParams["direction"] = 2
        case 3:
            print("向右滑动");
            self.PTZParams["direction"] = 3
        case 4:
            print("左上");
            self.PTZParams["direction"] = 4
        case 5:
            print("左下");
            self.PTZParams["direction"] = 5
        case 6:
            print("右上");
            self.PTZParams["direction"] = 6
        case 7:
            print("右下");
            self.PTZParams["direction"] = 7
        case 8:
            print("放大");
            self.PTZParams["direction"] = 8
        case 9:
            print("缩小");
            self.PTZParams["direction"] = 9
        case 10:
            print("近焦距");
            self.PTZParams["direction"] = 10
        case 11:
            print("远焦距");
            self.PTZParams["direction"] = 11
        
        default:
            break
        }

        
        ZGLiveManager.postGetAccessToken(url: kGetAccessToken, params: self.accessTokenParams, successClosure: { (accessToken) in

            self.PTZParams["accessToken"] = accessToken
            self.PTZParams["speed"] = 1
            ZGLiveManager.postStartPTZ(url: kVideoStartPTZ, params: self.PTZParams, successClosure: { (res) in
                
                if index != 10 && index != 11 {
                    DispatchQueue.main.asyncAfter(deadline: .now() + length) {
                        self.PTZParams.removeValue(forKey: "speed")
                        ZGLiveManager.postStopPTZ(url: kVideoStopPTZ, params: self.PTZParams, successClosure: { (res) in
                            
                        }) { (error) in
                            print(error)
                        }
                    }
                }
                
            }) { (error) in
                print(error)
            }

        }) { (error) in

        }
    }
    
    func initViews() {
        self.currentVC.view.addSubview(self.blanner!)
        
        self.currentVC.view.addSubview(self.middleView!)
        self.currentVC.view.bringSubviewToFront(self.middleView!)
        self.middleView!.blanner = blanner
        self.middleView!.showClosure = {[weak self] in
            if let weakSelf = self {
                weakSelf.aboveBtAction()
            }
        }
        
        self.middleView!.rotatClosure = {[weak self] (index, length) in
            if let weakSelf = self {
                EZOpenSDK.getDeviceInfo(weakSelf.deviceSerial) { (info, error) in
                    if info?.isSupportPTZ == true {
                        weakSelf.setRotatDirection(index, length)
                    }
                }
            }
        }
        
        self.currentVC.view.addSubview(self.topView!)
        self.currentVC.view.bringSubviewToFront(self.topView!)
        self.topView!.backClosure = {[weak self] in
            if let weakSelf = self {
                weakSelf.backAction()
            }
        }
        
//        self.currentVC.view.addSubview(self.bottomView!)
//        self.currentVC.view.bringSubviewToFront(self.bottomView!)
//        self.bottomView!.clickedClosure = {[weak self] (index) in
//            if let weakSelf = self {
//                weakSelf.hideAboveViews()
//                switch index {
//                case 0:
//                    if let img = weakSelf.screenshot() {
//                        weakSelf.saveImgs(image: img)
//                    }
//                case 1:
//                    weakSelf.choosePhotos()
//                default:
//                    break
//                }
//            }
//        }
//        self.bottomView!.pressClosure = {[weak self] (ges) in
//            
//            if let weakSelf = self {
//                weakSelf.hideAboveViews()
//                if ges.state == UIGestureRecognizer.State.began {
//                    weakSelf.middleView?.voiceView.isHidden = false
//                    weakSelf.talkPlayer!.startVoiceTalk()
//                    weakSelf.recoder.startRecord()
//                } else if ges.state == UIGestureRecognizer.State.ended {
//                    weakSelf.talkPlayer!.stopVoiceTalk()
//                    weakSelf.recoder.stopRecord()
//                    weakSelf.middleView?.voiceView.isHidden = true
//                }
//            }
//        }
        self.showView(isFullScreen: false)
        self.hideAboveViews()
        topView!.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(55)
        }
        middleView!.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
//        bottomView!.snp.makeConstraints { (make) in
//            make.bottom.equalToSuperview()
//            make.left.right.equalToSuperview()
//            make.height.equalTo(55)
//        }
    }
    
    func configureSDK(_ params: Dictionary<String, Any>) {
        initViews()
        canTakePhoto = params["canPhoto"] as? Bool ?? false
        self.bottomView?.btnCamera.isHidden = !canTakePhoto
        self.bottomView?.btnCloudSpread.isHidden = !canTakePhoto
        let titleName: String = params["titleName"] as? String ?? ""
        let accessToken: String = params["accessToken"] as! String
        let appKey: String = params["appKey"] as! String
        let appSecret: String = params["appSecret"] as! String
        let cameraNo: String = params["cameraNo"] as! String
        self.cameraNo = Int(cameraNo)!
        let deviceSerial: String = params["deviceSerial"] as! String
        self.deviceSerial = deviceSerial
        let videoId: String = params["videoId"] as? String ?? ""
        let monitoryPointId: String = params["monitoryPointId"] as? String ?? ""
        let loginToken: String = params["loginToken"] as? String ?? ""
        
        self.picParams = ["videoId": videoId, "monitoryPointId": monitoryPointId, "description": "不文明行为", "token": loginToken]
        self.PTZParams = ["deviceSerial": deviceSerial, "channelNo": Int(cameraNo)!, "speed": 1]
        self.accessTokenParams = ["appKey": appKey, "appSecret": appSecret]
        self.topView?.backBt.setTitle(titleName, for: .normal)
        
        EZOpenSDK.initLib(withAppKey: appKey)
        EZOpenSDK.setAccessToken(accessToken)
        player = EZOpenSDK.createPlayer(withDeviceSerial: deviceSerial, cameraNo: Int(cameraNo)!)
        player!.delegate = self
        player!.setPlayerView(blanner)
        
        talkPlayer = EZOpenSDK.createPlayer(withDeviceSerial: deviceSerial, cameraNo: Int(cameraNo)!)
        talkPlayer!.delegate = self
        talkPlayer!.audioTalkPressed(false)
        self.startLiveVideo(true)
    }
    
    func fullScreenAction() {
        self.totatingScreen(.landscapeRight)
    }
    func backAction() {
        self.totatingScreen(.portrait)
    }
    
    func hideAboveViews() {
        bottomView!.isHidden = true;
        topView!.isHidden = true;
    }
    
    func choosePhotos() {
        
        let tzvc = TZImagePickerController(maxImagesCount: 9, delegate: self)
        tzvc?.didFinishPickingPhotosHandle = {[weak self] (photos, assets, isOriginal) in
            var photoTimeArr = Array<String>()
            for (_, value) in assets!.enumerated() {
                let currentZoneDate = (value as! PHAsset).creationDate!
                photoTimeArr.append(currentZoneDate.format("yyyy-MM-dd HH:mm:ss"))
            }
            if let weakSelf = self {
                ZGLiveManager.postData(url: kImageUpload, params: nil, imageDatas: photos!, successClosure: { (res) in
                    
                    let resp = res as! Dictionary<String, Any>
                    let arr: Array<Dictionary<String, Any>> = resp["data"] as! Array<Dictionary<String, Any>>
                    var mArr = Array<Dictionary<String, String>>()
                    for (i, value) in arr.enumerated() {
                        var imgDict = Dictionary<String, String>()
                        let filePath: String = value["filePath"] as! String
                        let fileName: String = value["fileName"] as! String
                        imgDict["picPath"] = filePath + fileName
                        imgDict["captureDate"] = photoTimeArr[i]
                        mArr.append(imgDict)
                    }
                    weakSelf.picParams["pictureList"] = mArr
                    
                    ZGLiveManager.postInfo(url: kImageInfoUpload, params: weakSelf.picParams, successClosure: { (res) in
                        print(res)
                        print("上传成功")
                    }) { (error) in
                        print("上传失败")
                    }
                    
                }) { (error) in
                    
                }
                weakSelf.totatingScreen(UIInterfaceOrientation.landscapeRight)
            }
        }
        self.totatingScreen(UIInterfaceOrientation.portrait)
        self.currentVC.sg_present(tzvc!, animated: true)
    }
    
    func totatingScreen(_ ori: UIInterfaceOrientation) {
        
        let value = NSNumber(integerLiteral: ori.rawValue)
        UIDevice.current.setValue(value, forKey: "orientation")
    }
    
    func aboveBtAction() {
        if self.bottomView!.isHidden {
            UIView.animate(withDuration: 0.3) {
                self.topView!.isHidden = false
                self.bottomView!.isHidden = false
            }
        } else {
            UIView.animate(withDuration: 0.3) {
                self.topView!.isHidden = true
                self.bottomView!.isHidden = true
            }
        }
    }
    
    func leaveVideoPage() {
        self.stopLiveVideo()
        self.currentVC.canAllButUpsideDown = false
        EZOpenSDK.release(player)
        EZOpenSDK.release(talkPlayer)
        player = nil
        talkPlayer = nil
        self.currentVC.view.hideToastActivity()
    }
    
    func showView(isFullScreen: Bool) {
        
        if !isFullScreen {
            topView!.isHidden = !isFullScreen
            bottomView!.isHidden = !isFullScreen
        }
        blanner!.isHidden = !isFullScreen
        middleView!.isHidden = !isFullScreen
        currentVC.webView.isHidden = isFullScreen
    }
    
    func startLiveVideo(_ firstIn: Bool = false) {
        
        if let vc = self.currentVC, vc.canAllButUpsideDown {
            let currentOri = UIDevice.current.value(forKey: "orientation") as! NSNumber
            if (currentOri == 3 || currentOri == 4 || firstIn) {
                self.currentVC.view.makeToastActivity("CSToastPositionCenter")
            }
            player!.startRealPlay()
        }
    }
    
    func stopLiveVideo() {
        
        if let vc = self.currentVC, vc.canAllButUpsideDown {
            self.currentVC.view.hideToastActivity()
            player!.stopRealPlay()
        }
    }
    
    func reloadVideo() {
        self.stopLiveVideo()
        self.startLiveVideo()
    }
    
    func saveImgs(image: UIImage) {
        ZGCustomPhoto.saveImageInAlbum(image: image, albumName: "章广app") { (result) in
            
            DispatchQueue.main.async {
                switch result{
                case .success:
                    self.currentVC.view.makeToast("抓图成功，已保存至相册")
                case .denied:
                    self.currentVC.view.makeToast("抓图被拒绝")
                case .error:
                    self.currentVC.view.makeToast("抓图失败")
                }
            }
        }
    }
    
    //  播放器播放失败错误回调
    func player(_ player: EZPlayer!, didPlayFailed error: Error!) {
        print("player: \(player!), didPlayFailed: \(error!)")
        
        if self.maxCnt > 0 {
            self.reloadVideo()
            maxCnt -= 1
        } else {
            if (error.localizedDescription != "") {
                self.currentVC.view.makeToast(error.localizedDescription)
            } else {
                self.currentVC.view.makeToast("播放失败")
            }
        }
    }
    
    /**
     *  播放器消息回调
     *
     *  @param messageCode 播放器消息码，请对照EZOpenSDK头文件中的EZMessageCode使用
     */
    func player(_ player: EZPlayer!, didReceivedMessage messageCode: Int) {
        print("messageCode: \(messageCode)")
        if messageCode == 1 {//直播开始
            self.currentVC.view.hideToastActivity()
        } else if messageCode == 21 {//播放器检测到wifi变换过
//            self.reloadVideo()
        }
    }
    
    /**
     *  收到的数据长度（每秒调用一次）
     *
     *  @param dataLength 播放器流媒体数据的长度（每秒字节数）
     */
    func player(_ player: EZPlayer!, didReceivedDataLength dataLength: Int) {
        print("didReceivedDataLength: \(dataLength)")
    }
    
    /**
     *  收到的画面长宽值
     *
     *  @param height 高度
     *  @param width  宽度
     */
    func player(_ player: EZPlayer!, didReceivedDisplayHeight height: Int, displayWidth width: Int) {
        print("height: \(height), width: \(width)")
    }
    
    func getVoiceNum(num: Int) {
        var i = 0
        if num <= 1 {
            i = 0
        } else if num > 1 && num <= 2 {
            i = 1
        } else if num > 2 && num <= 3 {
            i = 2
        } else if num > 3 && num <= 4 {
            i = 3
        } else if num > 4 {
            i = 4
        }
        middleView?.voiceImage.image = UIImage(named: "voice\(i)")
    }
}

*/
